package com.theory.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.theory.mapper.SubjectMapper;
import com.theory.pojo.Subject;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class ExcelSubjectListener extends AnalysisEventListener<Subject> {


    private static final int BATH_COUNT = 1000;

    private List<Subject> list = new ArrayList<>();

    private SubjectMapper subjectMapper;

    public ExcelSubjectListener(SubjectMapper subjectMapper) {
        this.subjectMapper = subjectMapper;
    }


    @Override
    public void invoke(Subject data, AnalysisContext analysisContext) {
        data.setComplete(data.toString());

        list.add(data);

        if (list.size() >= BATH_COUNT) {
            saveData();
            list.clear();
        }

    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        subjectMapper.insertBatch(list);
    }

}
